<template>
  <div class="tab-content-container mx-5">
    <uploader action="/upload"
      class="d-flex align-items-center justify-content-center bg-light text-secondary circle mx-auto my-3"
      :beforeUpload="commonUploadCheck" :uploaded="uploadedData" @file-uploaded="onFileUploaded">
      <!--<template #loading>
        <div class="d-flex">
            如果添加了spinner-border 就会有两个旋转spinner展示 效果不佳 
          <div class=" text-secondary" role="status">
            <span class="visually-hidden">Loading...</span>
          </div>
          <h3>正在上传</h3>
        </div>
      </template>-->
      <template v-slot:uploaded="dataProps">
        <img :src="
          dataProps.uploadedData.data.url +
            '?x-oss-process=image/resize,m_fill,h_200,w_200'
        " />
      </template>
      <h3>点击上传头像</h3>
    </uploader>
    <validate-form ref="formRef" @form-submit="onFormSubmit">
      <div class="mb-3">
        <label class="form-label">
          {{ currentCategory.type === "profile" ? "用户名" : "专栏名" }}</label>
        <validate-input :rules="nameRules" placeholder="请输入名称" v-model="nameValue" type="text" />
      </div>
      <div class="mb-3">
        <label class="form-label">
          {{
          currentCategory.type === "profile" ? "个人简介" : "专栏简介"
          }}</label>
        <validate-input :rules="descRules" placeholder="请输入简介信息" v-model="descValue" rows="5" tag="textarea" />
      </div>
      <template #submit>
        <button class="btn btn-primary btn-large">
          {{
          currentCategory.type === "profile" ? "提交个人资料" : "提交专栏资料"
          }}
        </button>
      </template>
    </validate-form>
  </div>
</template>

<script lang="ts">
// 这个组件只用管好上传的功能就可以了，因为会设置两个editTab只是用z-index切换。所以不用担心数据缓存的问题
import { defineComponent, ref, computed, onMounted, PropType } from "vue";
import { useStore } from "vuex";
import { useRouter } from "vue-router";
import { ResponseType, ImageProps } from "@/store";
import Uploader from "../components/Uploader.vue";
import ValidateInput, { RulesProp } from "../components/ValidateInput.vue";
import ValidateForm from "../components/ValidateForm.vue";
import createMessage from "../components/createMessage";
import { commonUploadCheck } from "../helper";

type EditCategory = "profile" | "column";
// 约束props
interface CategoryType {
  type: EditCategory; // 传入当前的编辑类别 -> 控制submit是哪个form
  active: boolean; // 传入active状态 -> 控制表单的focus
}

export default defineComponent({
  name: "EditTab",
  components: {
    Uploader,
    ValidateInput,
    ValidateForm
  },
  props: {
    currentCategory: {
      type: Object as PropType<CategoryType>, // 约束props
      required: true
    }
  },
  setup(props) {
    const store = useStore();
    const router = useRouter();
    // 初始化的时候 userStore currentColumn 都加载
    const userStore = computed(() => {
      return store.state.user;
    });

    // 获取专栏的信息
    const currentColumn = computed(() => {
      return store.getters.getColumnById(userStore.value.column);
    });
    const uploadedData = ref();

    // 用户名 和 简介
    const nameValue = ref(userStore.value && userStore.value.nickName);
    const descValue = ref(userStore.value && userStore.value.description);
    // 编辑个人简介

    onMounted(async () => {
      const cid = userStore.value.column;
      await store.dispatch("fetchColumn", cid);
      // console.log(store.getters.getColumnById(userStore.value.column));
      if (props.currentCategory.type === "column") {
        const { title, description } = currentColumn.value;
        nameValue.value = title;
        descValue.value = description;
        if (currentColumn.value && currentColumn.value.avatar) {
          const { avatar } = currentColumn.value;
          uploadedData.value = { data: avatar };
        } else {
          uploadedData.value = null;
        }
      } else if (props.currentCategory.type === "profile") {
        const { nickName, description } = userStore.value;
        nameValue.value = nickName;
        descValue.value = description;
        if (userStore.value && userStore.value.avatar) {
          const { avatar } = userStore.value;
          uploadedData.value = { data: avatar };
        }
      }
    });
    let imageId = "";
    const nameRules: RulesProp = [
      { type: "required", message: "名字不能为空" }
    ];
    const descRules: RulesProp = [
      { type: "required", message: "详情不能为空" }
    ];
    // 上传文件之后 预览图片
    const onFileUploaded = (rawData: ResponseType<ImageProps>) => {
      if (rawData.data._id) {
        imageId = rawData.data._id;
      }
    };
    const onFormSubmit = (result: boolean) => {
      if (result) {
        let payload: any = {};
        if (
          props.currentCategory.type === "profile" &&
          props.currentCategory.active
        ) {
          payload = {
            _id: userStore.value._id,
            nickName: nameValue.value,
            description: descValue.value
          };
        } else if (
          props.currentCategory.type === "column" &&
          props.currentCategory.active
        ) {
          payload = {
            _id: currentColumn.value._id,
            title: nameValue.value,
            description: descValue.value
          };
        } else return;
        if (imageId) {
          payload.avatar = imageId;
        }
        const actionName =
          props.currentCategory.type === "profile"
            ? "updateUser"
            : "updateColumn";
        const sendData =
          props.currentCategory.type === "profile"
            ? {
              id: userStore.value._id,
              payload
            }
            : {
              id: currentColumn.value._id,
              payload
            };
        store.dispatch(actionName, sendData).then(() => {
          createMessage("修改成功", "success", 2000, "跳转到首页");
          setTimeout(() => {
            router.push("/");
          }, 2000);
        });
      }
    };
    return {
      onFileUploaded,
      uploadedData,
      onFormSubmit,
      commonUploadCheck,
      nameRules,
      descRules,
      nameValue,
      descValue
    };
  }
});
</script>

<style lang="less">
// .update-profile-page {
//   width: 700px;
// }
// 注意：这里想要传递给组件的样式class不能添加scoped
.circle {
  width: 200px;
  height: 200px;
  border-radius: 200px;
  overflow: hidden;
  cursor: pointer;
  border: 1px solid #efefef;
}
</style>
